# -*-coding:utf-8 -*-

from django.contrib.auth import authenticate, login
from django.http import HttpResponse


def index(request):
    return HttpResponse("Hello, world.")


from .serializers import *
from rest_framework import status
# from rest_framework import authentication_classes
from rest_framework.response import Response
from rest_framework.authentication import BasicAuthentication, SessionAuthentication
from rest_framework.decorators import api_view, permission_classes, authentication_classes
from rest_framework.permissions import IsAuthenticated, AllowAny
from .models import Project
import os

from client_data_tool.excel_lua_tools import ExcelToLua
from client_data_tool.combine_lua_tool import process_combine
from client_data_tool.upload_tool import UploadTool
from .m_status import MStatus

import logging
logger = logging.getLogger('canglongadmin.app')

# from django.shortcuts import redirect

CANGLONG_CLIENT_STR = 'm_status_deploy_client_canglong'
UPLOAD_STR = "上传："
PARSE_EXCEL_STR = "转表："
PROCESS_COMBINE_STR = "编译："
DEPLOY_STR = "部署："

import tempfile


@api_view(['POST'])
@permission_classes((AllowAny,))
@authentication_classes((BasicAuthentication,))
def user_login_view(request):
    try:
        username = request.data.get('username')
        password = request.data.get('password')
        user = authenticate(username=username, password=password)
        x = request.user
        print(user)
        if user:
            serializer = LoginSerializer({'id': user.id, 'username': user.username})
            login(request, user)
            return Response(serializer.data)
        return Response(status=status.HTTP_401_UNAUTHORIZED, data={'msg': '登陆失败，请检查用户名密码'})
    except User.DoesNotExist:
        return Response(status=status.HTTP_401_UNAUTHORIZED, data={'msg': '登陆失败，请检查用户名密码'})


@api_view(['GET'])
@permission_classes((IsAuthenticated,))
@authentication_classes((SessionAuthentication,))
def get_project_list_view(request):
    try:
        user = request.user
        project_list = Project.objects.all()
        if project_list:
            serializer = ProjectSerializer(project_list, many=True)
            return Response(serializer.data)
        return Response(data={'msg': '还没有项目哦'})
    except:
        return Response(data={'msg': '查询出错，请联系开发者'})


@api_view(['GET'])
@permission_classes((IsAuthenticated,))
@authentication_classes((SessionAuthentication,))
def get_user_list_view(request):
    try:
        user_list = User.objects.all()
        if user_list:
            for user in user_list:
                # user.permissions = user.user_permissions.values()
                user.user_group = user.groups.values()
            serializer = UserSerializer(user_list, many=True)
            return Response(serializer.data)
        return Response(data={'msg': '还没有用户哦'})
    except User.DoesNotExist:
        return Response(data={'msg': '查询出错，请联系开发者'})


@api_view(['POST'])
@permission_classes((IsAuthenticated,))
@authentication_classes((SessionAuthentication,))
def get_deploy_profiles(request):
    try:
        profile_list = DeployProfile.objects.all()
        if profile_list:
            serializer = DeployProfileSerializer(profile_list, many=True)
            return Response(serializer.data)
        return Response(data={'msg': '还没有配置哦'})
    except Exception as e:
        logger.error("查询配置出错：" + str(e))
        return Response(data={'msg': '查询出错，请联系开发者'})


@api_view(['POST'])
@permission_classes((IsAuthenticated,))
@authentication_classes((SessionAuthentication,))
def clean_temp_folder(request):
    request.session[CANGLONG_CLIENT_STR] = None
    config = request.data
    if config == {}:
        return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                        data={'redirect': '/deploylist', 'msg': '会话过期，请重新操作', 'code': 500})

    _status = request.session[CANGLONG_CLIENT_STR] = MStatus(
        [UPLOAD_STR, PARSE_EXCEL_STR, PROCESS_COMBINE_STR, DEPLOY_STR], request.session, CANGLONG_CLIENT_STR, config)

    upload_temp_dir = tempfile.mkdtemp()
    logger.info("upload_temp_dir：" + upload_temp_dir)
    _status.setStore(upload_temp_dir=upload_temp_dir)

    request.session.modified = True
    return Response(data={'msg': '更新成功', 'code': 200})


@api_view(['POST'])
@permission_classes((IsAuthenticated,))
@authentication_classes((SessionAuthentication,))
def upload_data(request):
    # 进入上传状态
    _status = request.session.get(CANGLONG_CLIENT_STR, False)
    if not _status:
        return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                        data={'msg': '错误：会话过期，请重新操作'})
    else:

        try:
            fileList = request.FILES.values()
            for f in fileList:
                destination = open(os.path.join(_status.getStore('upload_temp_dir'), f.name), 'wb+')  # 打开特定的文件进行二进制的写操作
                for chunk in f.chunks():  # 分块写入文件
                    destination.write(chunk)
                destination.close()
            return Response(data={'msg': '上传成功', 'code': 200})
        except Exception as e:
            logger.error("文件上传失败：" + e.__str__())
            return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR, data={'msg': '上传失败', 'trace': e.__str__()})


@api_view(['POST'])
@permission_classes((IsAuthenticated,))
@authentication_classes((SessionAuthentication,))
def process_parse_client_data(request):
    _status = request.session.get(CANGLONG_CLIENT_STR, False)
    if _status:
        _status.update_status(UPLOAD_STR, 1)
        upload_temp_dir = _status.getStore('upload_temp_dir')

        logger.info("upload_temp_dir：" + upload_temp_dir)
        # print('upload_temp_dir:', upload_temp_dir)
        excel_parse_dist = tempfile.mkdtemp()

        logger.info("excel_parse_dist：" + excel_parse_dist)
        # print('dist_temp:', excel_parse_dist)
        _status.setStore(excel_parse_dist=excel_parse_dist)

        def _callback_one_file(file_path, progress, result, status_text):
            _status.update_status(PARSE_EXCEL_STR, progress)
            _status.append_output(PARSE_EXCEL_STR, status_text)
            # _status.fail = True
            print(status_text)
            print(PARSE_EXCEL_STR, progress)

        def _callback_over(parse_list):
            _status.append_output(PARSE_EXCEL_STR, '处理完成')
            logger.info("process_over：" + str(parse_list))


        ExcelToLua.parse_folder(upload_temp_dir, excel_parse_dist, one_file_callback=_callback_one_file,
                                process_over_callback=_callback_over)

        return Response(data={'msg': '等待成功', 'code': 200})

    else:
        return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                        data={'msg': '错误：会话过期，请重新操作'})


@api_view(['POST'])
@permission_classes((IsAuthenticated,))
@authentication_classes((SessionAuthentication,))
def process_combine_client_data(request):
    _status = request.session.get(CANGLONG_CLIENT_STR, False)
    if _status:
        excel_parse_dist = _status.getStore('excel_parse_dist')
        combine_parse_dist = tempfile.mkdtemp()

        _status.setStore(combine_parse_dist=combine_parse_dist)
        # print('combine_parse_dist:', combine_parse_dist)
        logger.info('combine_parse_dist:' + combine_parse_dist)
        def callback(str, progress, fail):
            _status.update_status(PROCESS_COMBINE_STR, progress)
            _status.append_output(PROCESS_COMBINE_STR, str)
            print(PROCESS_COMBINE_STR, progress)
            print(PROCESS_COMBINE_STR, str)
            if fail:
                _status.setFail()

        process_combine(excel_parse_dist, combine_parse_dist, '.lua', step_callback=callback)
        return Response(data={'msg': '等待成功', 'code': 200})
    else:
        return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                        data={'msg': '错误：会话过期，请重新操作'})


@api_view(['POST'])
@permission_classes((IsAuthenticated,))
@authentication_classes((SessionAuthentication,))
def process_upload(request):
    _status = request.session.get(CANGLONG_CLIENT_STR, False)
    if _status:

        def callback(str, progress, fail):
            _status.update_status(DEPLOY_STR, progress)
            _status.append_output(DEPLOY_STR, str)
            print(DEPLOY_STR, progress)
            print(DEPLOY_STR, str)
            if fail:
                _status.setFail()
                logger.error('部署失败：' + str)

        try:
            config = eval(_status.config['interface_params'])
        except Exception as e:
            logger.error('部署失败，配置不正确：' + e.__str__())
            return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                            data={'msg': '错误：配置不正确'})

        UploadTool(config, _status.getStore('combine_parse_dist'), callback).process_upload()

        # process_combine(excel_parse_dist, combine_parse_dist, '.lua',step_callback = callback)
        return Response(data={'msg': '等待成功', 'code': 200})
    else:
        return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                        data={'msg': '错误：会话过期，请重新操作'})


@api_view(['POST'])
@permission_classes((IsAuthenticated,))
@authentication_classes((SessionAuthentication,))
def get_process_status(request):
    status = request.session.get(CANGLONG_CLIENT_STR, False)
    if status:
        return Response(data={
            'status': status.getStatus(),
            'statusList': status.getStatusList(),
        })
    else:
        return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                        data={'msg': '错误：会话过期，请重新操作'})
